
package com.joolun.cloud.mall.api.controller;

import cn.hutool.core.util.StrUtil;
import com.joolun.cloud.common.core.constant.CommonConstants;
import com.joolun.cloud.common.core.constant.SecurityConstants;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.common.data.tenant.TenantContextHolder;
import com.joolun.cloud.mall.api.service.ThemeMobileService;
import com.joolun.cloud.mall.api.util.ApiUtil;
import com.joolun.cloud.mall.common.constant.MallConstants;
import com.joolun.cloud.mall.common.feign.FeignWxAppService;
import com.joolun.cloud.weixin.common.constant.ConfigConstant;
import com.joolun.cloud.weixin.common.entity.WxApp;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * 移动端主题配置
 *
 * @author www.joolun.com
 * @date 2020-06-04 14:28:15
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/thememobile")
@Api(value = "thememobile", tags = "移动端主题配置API")
public class ThemeMobileController {

    private final ThemeMobileService themeMobileService;
	private final FeignWxAppService feignWxAppService;

	/**
	 * 查询主题配置
	 * @return R
	 */
	@ApiOperation(value = "查询主题配置")
	@GetMapping()
	public R get(HttpServletRequest request) {
		//获取header中的TENANT_ID
		String tenantIdHeader = request.getHeader(CommonConstants.TENANT_ID);
		if(StrUtil.isNotBlank(tenantIdHeader)){
			TenantContextHolder.setTenantId(tenantIdHeader);
		}else{
			String clientType = ApiUtil.getClientType(request);
			if(!MallConstants.CLIENT_TYPE_MA.equals(clientType)){
				return R.failed("租户ID不能为空");
			}
			//小程序端通过appId获取租户ID
			String appIdHeader = ApiUtil.getAppId(request);
			WxApp wxApp = feignWxAppService.getById(appIdHeader, SecurityConstants.FROM_IN).getData();
			if(wxApp == null){
				return R.failed("请在后台配置小程序信息");
			}
			TenantContextHolder.setTenantId(wxApp.getTenantId());
		}

		return R.ok(themeMobileService.getByTenantId(TenantContextHolder.getTenantId()));
	}

}
